package cn.it.service.impl;

import cn.it.constant.MessageConstant;
import cn.it.dao.MemberDao;
import cn.it.dao.OrderDao;
import cn.it.dao.OrderSettingDao;
import cn.it.entity.PageResult;
import cn.it.entity.QueryPageBean;
import cn.it.entity.Result;
import cn.it.pojo.Member;
import cn.it.pojo.Order;
import cn.it.pojo.OrderSetting;
import cn.it.service.OrderService;
import cn.it.utils.DateUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private MemberDao memberDao;


    @Autowired
    private OrderSettingDao orderSettingDao;


    @Override
    public Result order(Map map) throws Exception {
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");//预约日期
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null) {
            //指定日期没有进行预约设置，无法完成体检预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number) {
            //已经约满，无法预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        //获取用户页面输入的手机号
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);

        if (member != null) {
            //判断是否在重复预约
            Integer memberId = member.getId();//会员ID
            Date order_Date = DateUtils.parseString2Date(orderDate);//预约日期
            String setmealId = (String) map.get("setmealId");//套餐ID
            Order order = new Order(memberId, order_Date, Integer.parseInt(setmealId));

            //根据条件进行查询
            List<Order> orderList = orderDao.findByCondition(order);
            if (orderList != null && orderList.size() > 0) {
                //说明用户在重复预约，无法完成再次预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        } else {
            //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册
        }

        //5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID

        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        return new Result(true,MessageConstant.ORDERSETTING_SUCCESS,order.getId());
    }

    //根据预约ID查询预约相关信息（体检人姓名、预约日期、套餐名称、预约类型）
    @Override
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if (map!=null){
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",DateUtils.parseDate2String(orderDate));

        }
        return map;
    }

    /**
     * 分页条件查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Order> page = orderDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 确定预约
     * @param id
     */
    @Override
    public void ConfirmAppointment(Integer id) {
        orderDao.ConfirmAppointment(id);
        Order order = orderDao.findById(id);
//            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,"15623374033","123456");
        System.out.println("短信:" + "[体检通知]请于"+order.getOrderDate()+
                "参加体检。体检注意：体检前空腹8小时以上，体检当天早上，请勿饮食饮水，如需服用降压药物，" +
                "请一口水顺服。请携带当天的大便标本(体检当天可在医院领便检盒)。如需调整时间，请与医务室联系。" +
                "详情咨询医务室8888888");
    }

    /**
     * 取消预约
     * @param id
     * @throws Exception
     */
    @Override
    public void cancelReservation(Integer id) throws Exception {
        Order order = orderDao.findById(id);
        if ("未到诊".equals(order.getOrderStatus())){
            orderDao.deleteById(id);
            System.out.println("短信:" + "已经成功取消预约");
        }else {
            throw new Exception();
        }

    }

    /**
     * 添加预约
     */
    @Override
    public void add(Integer[] setmealIds, Date orderDate, Member member) throws Exception {
        for (Integer setmealId : setmealIds) {
            Order order = new Order();
            order.setSetmealId(setmealId);
            order.setOrderDate(orderDate);

            //使用当前时间毫秒值生成档案号
            member.setFileNumber(String.valueOf(new Date().getTime()));

            //添加用户
            memberDao.add(member);

            order.setMemberId(member.getId());

            order.setOrderType("电话预约");
            order.setOrderStatus("未到诊");
            //添加预约信息
            orderDao.add(order);
        }
    }

    /**
     * 批量取消预约
     * @param orderIds
     * @throws Exception
     */
    @Override
    public void batchCancelReservation(Integer[] orderIds) throws Exception {

        for (Integer id : orderIds) {
            Order order = orderDao.findById(id);
            if ("未到诊".equals(order.getOrderStatus())){
                orderDao.deleteById(id);
                System.out.println("短信:" + "已经成功取消预约");
            }else {
                throw new Exception();
            }
        }

    }
}
